#!/usr/bin/env python
#coding:utf-8
"""
  Author:  程勇 --<>
  Purpose: 动脑学院17节作业
  Created: 2018/3/6
"""

import os
import pickle
import json
from time import sleep
from copy import copy,deepcopy
from io import StringIO,BytesIO

'''1.使用pickle,json(注意:两个模块)
把字典a_dict = [1,2,3,[4,5,6]]
序列化与反序列化,序列化,保存到文件名为serialize.txt文件里面,然后大开,并读取数据
反序列化为python对象加载到内存,并打印输出
尝试序列化/反序列非文件中,直接操作'''
a_dict = [1,2,3,[4,5,6]]

#pickle模块
def question_01_p():
    
    with open('serialize.txt','wb') as saveText:
        pickle.dump(a_dict,saveText,0)
    
    sleep(3)    
    
    with open('serialize.txt','rb') as readText:
        print(pickle.load(readText))
        
    sleep(3)
    print('*'*33)
    
    #不存入文件
    p_not = pickle.dumps(a_dict)
    print('非文件数据:',pickle.loads(p_not))

#json模块
def question_01_j():
    with open('serialize.txt','w',encoding='utf-8') as saveText:
        json.dump(a_dict,saveText)
        
    sleep(3)
    
    with open('serialize.txt','r',encoding='utf-8') as readText:
        print('存入文件数据:',json.load(readText))
        
    sleep(3)
    print('*'*33)
    #不存入文件
    j_not = json.dumps(a_dict)
    print('非文件数据:',json.loads(j_not))
    
'''2.自己写代码对比深浅拷贝的区别,写完代码然后看看运行结果,然后分析原因
   比如：a_list=[1,2,3,4,[8,9,0]]'''
def question_02():
    #浅拷贝
    b_list = [1,2,3,4,[8,9,0]]
    x_list = list(b_list)
    y_list = copy(b_list)
    
    x_list[2] = 'change'
    print(b_list)
    print(x_list)
    print(y_list)
    
    x_list[4][1] = 'xxx'
    print(b_list)
    print(x_list)
    print(y_list)
    
    print('浅拷贝，最外层数据不共享，改变不涉及别的；次层数据共享，牵一发，动全身')
    
    #深拷贝
    b_list = [1,2,3,4,[8,9,0]]
    z_list = deepcopy(b_list)
    
    z_list[3] = 'deep'
    print(b_list)
    print(z_list)
    
    z_list[4][2] = 'second'
    print(b_list)
    print(z_list)    
    
    print('深拷贝，数据都完全独立，不共享')

'''3.分别写代码完成内存缓冲区文本数据和二进制数据的读/写操作'''
def question_03():
    #文本数据
    str_f = StringIO()
    str_f.write('samsumg发布会')
    str_f.writelines(['s9 64g','s9 128g','s9 256g'])
    print(str_f.getvalue())
    
    sleep(3)
    
    f = StringIO('Hello!\nHi!\nGoodbye!')
    while True:
        s = f.readline()
        if s == '':
            break
        print(s.strip())    

    #二进制
    f = BytesIO()
    f.write('中文'.encode('utf-8'))
    print(f.getvalue())
    
    sleep(3)
    
    f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
    print(f.read().decode())
    
def main():
    question_01_j()
    
    question_01_p()
    
    question_02()
    
    question_03()
    
if __name__ == '__main__':
    main()